<template>
  <div class="collection-page">
    <div class="collection-header">
      <h2>我的收藏</h2>
      <p v-if="collectionList != null">共收藏 {{ collectionList.length }} 件商品</p>
    </div>

    <el-collapse v-model="activeNames" class="collection-collapse" v-if="collectionList != null">
      <el-collapse-item
        v-for="(item, index) in collectionList"
        :key="item.id"
        :name="index + 1"
      >
        <template slot="title">
          <div class="collection-title">
            <div class="title-image">
              <el-image
                :src="url + item.fileName"
                fit="cover"
                :preview-src-list="[url + item.fileName]"
              >
                <!-- <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div> -->
              </el-image>
            </div>
            <div class="title-info">
              <div class="product-name">{{ item.name }}</div>
              <div class="product-price">¥{{ item.price.toFixed(2) }}</div>
            </div>
          </div>
        </template>
        
        <div class="collection-actions">
          <el-table :data="[item]" border class="collection-table">
            <el-table-column
              label="商品信息"
              header-align="center"
              align="center"
              width="300"
            >
              <template slot-scope="scope">
                <div class="product-details">
                  <div>商品编号: {{ scope.row.productCode }}</div>
                  <div>收藏时间: {{ formatDate(scope.row.collectTime) }}</div>
                     <div>库存状态: 
                    <span :class="scope.row.stock > 0 ? 'in-stock' : 'out-stock'">
                      {{ scope.row.stock > 0 ? '有货' : '无货' }}
                    </span>
                  </div>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column
              label="操作"
              header-align="center"
              align="center"
              width="300"
            >
              <template slot-scope="scope">
                <div class="action-buttons">
                  
                  <!-- <el-button 
                    type="success" 
                    size="small" 
                    icon="el-icon-shopping-cart" 
                    @click="addToCart(scope.row)"
                    :disabled="scope.row.stock <= 0"
                  >
                    加入购物车
                  </el-button> -->
                  
                  <el-button 
                    type="danger" 
                    size="small" 
                    icon="el-icon-delete" 
                    @click="deleteCollection(scope.row.id, index)"
                  >
                    取消收藏
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>

    <!-- 空状态显示 -->
    <div v-if="collectionList != null && collectionList.length === 0" class="empty-collection">
      <el-empty description="暂无收藏商品" />
      <el-button type="primary" @click="goShopping">去逛逛</el-button>
    </div>

    <!-- 分页 -->
    <!-- <div v-if="collectionList && collectionList.length > 0" class="pagination-container">
      <el-pagination
        prev-text="上一页"
        next-text="下一页"
        background
        @current-change="handleCurrentChange"
        :page-size="pageSize"
        :current-page="pageNum"
        layout="prev, pager, next, jumper"
        :total="pageInfo.total"
      ></el-pagination>
    </div> -->
  </div>
</template>

<script>
import Vue from "vue";
import { 
  Collapse, 
  CollapseItem, 
  Table, 
  TableColumn, 
  Image, 
  Pagination, 
  Button, 
  Empty,
  Icon
} from "element-ui";

Vue.use(Collapse);
Vue.use(CollapseItem);
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Image);
Vue.use(Pagination);
Vue.use(Button);
Vue.use(Empty);
Vue.use(Icon);

export default {
  data() {
    return {
      pageNum: 1,
      pageSize: 5,
      userId: null,
      collectionList: [],
      /* pageInfo: {
        total: 0
      }, */
      activeNames: [1,2,3,4,5,6],
      url: sessionStorage.getItem("imagesDir") || ""
    };
  },
  methods: {
    // 处理分页变化
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getCollectionList();
    },
    getUserId() {
      this.$http
        .post(
          "/api/address/getUserId",
          "token=" + sessionStorage.getItem("token")
        )
        .then((res) => {
          this.userId = res.data.userId;
          this.getCollectionList();
        });
    },
    // 获取收藏列表
    getCollectionList() {
      this.$axios({
        url: "/api/collection/list",
        method: "POST",
        data: {
          userId: this.userId,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      }).then((response) => {
        console.log("收藏列表数据:", response);
        // this.pageInfo = response.data.pageInfo;
        this.collectionList = response.data.products;
        // 默认展开第一个
        /* if (this.collectionList && this.collectionList.length > 0 && this.activeNames.length === 0) {
          this.activeNames = ['1'];
        } */
      }).catch((error) => {
        this.$message.error("获取收藏列表失败，请重试");
        console.error("获取收藏列表错误:", error);
      });
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return date.toLocaleString();
    },

    
    
    /* // 关注店铺
    handleFollow(item) {
      this.$axios({
        url: `/api/shop/follow/${item.shopId}`,
        method: "post"
      }).then(() => {
        this.$message.success("关注成功");
        item.isFollowed = true;
      }).catch(() => {
        this.$message.error("关注失败，请重试");
      });
    }, */
    
    // // 加入购物车
    // addToCart(item) {
    //   this.$axios({
    //     url: "/api/cart/add",
    //     method: "post",
    //     data: {
    //       productId: item.id,
    //       quantity: 1
    //     }
    //   }).then(() => {
    //     this.$message.success("已加入购物车");
    //   }).catch(() => {
    //     this.$message.error("加入购物车失败，请重试");
    //   });
    // },
    
    // 删除收藏
    deleteCollection(productId, index) {
      this.$messageBox.confirm("确定要取消收藏这件商品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$axios({
          url: `/api/collection/remove`,
          method: "post",
          data: {
            userId: this.userId,
            productId,
          }
        }).then(() => {
          // 从列表中移除
          this.collectionList.splice(index, 1);
          this.$message.success("取消收藏成功");
          // this.pageInfo.total--;
          /* // 如果当前页为空，且不是第一页，则返回上一页
          if (this.collectionList.length === 0 && this.pageNum > 1) {
            this.pageNum--;
            this.getCollectionList();
          } */
        }).catch(() => {
          this.$message.error("取消收藏失败，请重试");
        });
      }).catch(() => {
        this.$message.info("已取消操作");
      });
    },
    
    // 去购物
    goShopping() {
      // 跳转到商品列表页
      this.$router.push({
        name: 'GoodsList',
        query: {
          searchTxt: ''
        }
      });
    }
  },
  created() {
    let loginName = sessionStorage.getItem("loginName");
    if(!loginName) {
      this.$message.error("权限不足，将回到首页！")
      this.$router.push({
        name: 'IndexCenter'
      })
      return;
    }
    
    this.getUserId();
  }
};
</script>

<style scoped>
.collection-page {
  width: 75%;
  float: right;
  padding: 20px;
  background-color: #f9f9f9;
  min-height: calc(100vh - 120px);
}

.collection-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.collection-header h2 {
  margin: 0 0 10px 0;
  color: #333;
}

.collection-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.collection-collapse {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.collection-title {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.title-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.title-image /deep/ .el-image {
  width: 100%;
  height: 100%;
}

.title-info {
  flex: 1;
}

.product-name {
  font-weight: 500;
  margin-bottom: 5px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 800px;
}

.product-price {
  color: #f56c6c;
  font-weight: bold;
}

.collection-actions {
  padding: 10px 0;
}

.collection-table {
  width: 100%;
}

.product-details {
  text-align: left;
  line-height: 1.8;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.in-stock {
  color: #67c23a;
}

.out-stock {
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.empty-collection {
  
  text-align: center;
  padding: 50px 0;
  background-color: #fff;
  border-radius: 4px;
}

.empty-collection /deep/ .el-empty {
  margin-bottom: 20px;
}
</style>
